import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import {  ControllerType } from "@/components/items-list/ItemsList";
import {Button, Col, Form, Input, Row,Divider, Table, ConfigProvider, Layout, Tree,Modal,Checkbox} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import Templates from "@/services/templates";
import notification from "@/services/notification";
import {get} from "lodash";
// import { createHashHistory } from 'history';
// const hashHistory = createHashHistory();
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
import Enums from "@/services/enums";
import CreateTemplatesDialog from "@/components/contract/settings/TemplatesDialog";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import routes from "@/services/routes";
const {Sider } = Layout;
const { confirm } = Modal;
class TemplatesList extends React.Component {
  state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    code: '',
    name: '',
    orgunitname:'',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
    views:false,
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      orgunitname:'',
      type: this.state.selectedKeys,
      selectedTitle: this.state.selectedTitle,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     Templates.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
            selectedKeys: params.type,
            selectedTitle: params.selectedTitle,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      orgunitname:this.state.orgunitname,
      type: '',
      selectedTitle: "",
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if(this.state.views){
      notification.error("查看模式不能删除，删除失败！");
      return;
    }
    if(record.is_active)
    {
       notification.error("只有在停用状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除合同模板?',
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Templates.delete(record).then(()=>{
          notification.success("合同模板删除成功.");
          let param={
            page: this.state.page,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            orgunitname:this.state.orgunitname,
            type: this.state.selectedKeys,
            selectedTitle: this.state.selectedTitle,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  handleview = record => {
        let param={
          page: this.state.page,
          pagesize: this.state.pagesize,
          code: this.state.code,
          name: this.state.name,
          orgunitname:this.state.orgunitname,
          type: this.state.selectedKeys,
          selectedTitle: this.state.selectedTitle,
    }
    record.views=true;
    CreateTemplatesDialog.showModal({templates: record})
    .onClose((result = {}) => {
    if (result.success) {
    this.fetch(param);
    }
    }).onDismiss(() => {
    navigateTo("templates", true);
    });
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      code: this.state.code,
      name: this.state.name,
      type: this.state.selectedKeys,
       selectedTitle: "",
    }
    this.fetch(param);
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      let views=false;
      if(this.props.views==="1"){
        views=true;
      }
      this.setState({
        loading: false,
        gData: datas,
        views:views,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            type: selectedKeys[0],
            selectedTitle: e.node.props.title,
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
  handleUpdate = record => {
    if(this.state.views){
      notification.error("查看模式不能修改！");
      return;
    }
            let param={
                  page: this.state.page,
                  pagesize: this.state.pagesize,
                  code: this.state.code,
                  name: this.state.name,
                  type: this.state.selectedKeys,
                  selectedTitle: this.state.selectedTitle,
            }
    record.views=false;
    CreateTemplatesDialog.showModal({templates: record})
    .onClose((result = {}) => {
        if (result.success) {
            this.fetch(param);
        }
      }).onDismiss(() => {
        navigateTo("templates", true);
      });
  };
  handleadd = () => {
            let param={
              page: 1,
              pagesize: this.state.pagesize,
              code: this.state.selectedKeys,
            }
     Templates.gettypelist(param).then(data => {
       var  list = data.data[0];
       // var arr = Array.from(data)
       // var array = Object.keys(data).map(function(el){
       //      return data[el];
       //  });
        CreateTemplatesDialog.showModal({templates: {id:0,type: list.type,typename: list.typename,views:false}})
        .onClose((result = {}) => {
            if (result.success) {
               param={
                  page: 1,
                  pagesize: this.state.pagesize,
                  code: this.state.code,
                  name: this.state.name,
                  type: this.state.selectedKeys,
                  selectedTitle: this.state.selectedTitle,
                }
                this.fetch(param);
            }
          }).onDismiss(() => {
          //  navigateTo("templates", true);
          });
    }).catch(error => {
        CreateTemplatesDialog.showModal({templates: {id:0,type: "",typename: "",views:false}})
        .onClose((result = {}) => {
            if (result.success) {
               param={
                  page: 1,
                  pagesize: this.state.pagesize,
                  code: this.state.code,
                  name: this.state.name,
                  type: this.state.selectedKeys,
                  selectedTitle: this.state.selectedTitle,
                }
                this.fetch(param);
            }
          }).onDismiss(() => {
          //  navigateTo("templates", true);
          });
        });
  };
onDragEnter = info => {
    console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '模板编码',
        key: 'code',
        dataIndex: 'code',
        render: (text, record) => (
          <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
        ),
        sorter: (a, b) => a.code > b.code ? 1 : -1
      },
      {
        title: '模板名称',
        dataIndex: 'name',
        key: 'name',
        sorter: (a, b) => a.name > b.name ? 1 : -1
      },
      {
        title: '部门',//合同类别
        dataIndex: 'orgunitname',
        key: 'orgunitname',
        sorter: (a, b) => a.orgunitname > b.orgunitname ? 1 : -1
      },
      // {
      //   title: '合同类别',//合同类别
      //   dataIndex: 'typename',
      //   key: 'typename',
      //   sorter: (a, b) => a.typename > b.typename ? 1 : -1
      // },
      {
        title: '启用',
        dataIndex: 'is_active',
        key: 'is_active',
        render: (text, record) => (
          <span>
            <Checkbox checked={text}></Checkbox>
          </span>
        ),
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable" onClick={() => this.handleview(record)}>预览</a>
            <Divider type="vertical" />
            <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
      {/*<div className="page-dashboard-list">*/}
        <div className="container">
          <PageHeader title="合同模板列表"/>
        </div>
      <Layout>
          <Layout>
            {/* <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                // showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider> */}
        <Layout style={{ padding: '0 24px 24px' }}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="模板编码">
              <Input
                value={this.state.code}
                onChange={e => this.setState({code:e.target.value})}
                placeholder="模板编码"
                autoFocus
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="模板名称">
              <Input
                value={this.state.name}
                onChange={e => this.setState({name:e.target.value})}
                placeholder="模板名称"
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="部门">
              <Input
                value={this.state.orgunitname}
                onChange={e => this.setState({orgunitname:e.target.value})}
                placeholder="部门"
                autoFocus
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				 {!this.state.views && (<Col span={10}>
          <Button type="primary" onClick={() => this.handleadd()} >
            <i className="fa fa-plus m-r-5" />
            新增
          </Button>
				  </Col>)}
				  <Col span={10}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
        </Row>
      </Form>
                 <div>
                      <Table rowKey='id'
                             columns={listcolumns}
                             dataSource={this.state.data}
                             pagination={paginationProps}
                             loading={this.state.loading}
                             onChange={this.handleTableChange}
                      />
                 </div>
        </Layout>
        </Layout>
       </Layout>
  </ConfigProvider>
    );
  }
}

routes.register(
  "Templates.List",
  routeWithUserSession({
    path: "/templates",
    title: "合同模板",
    render: pageProps => <TemplatesList {...pageProps} views="0"/>,
  })
);
routes.register(
  "Templates.List2",
  routeWithUserSession({
    path: "/templates/views",
    title: "合同模板查看",
    render: pageProps => <TemplatesList {...pageProps} views="1"/>,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/templates",
//     title: "合同模板",
//     render: pageProps => <TemplatesList {...pageProps} />,
//   }),
// ];
